﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lidgren.Network;


namespace Kaleta.Network
{
    /// <summary>
    /// This class is used to get average latency statistics.
    /// </summary>
    public class LatencyTester
    {
        private double timePacketSend;
        private float timeLastRoundtrip;
        private NetLatencyObject netLatencyObject;

        public LatencyTester()
        {
           
        }

        /// <summary>
        /// Starts the latency test. Can be invoked outside the Update() method. If the test is already started, method call is ignored.
        /// Channel is Reliable in order.
        /// </summary>
        public void RunTest()
        {
            if (this.netLatencyObject == null)
            {
                this.netLatencyObject = new NetLatencyObject();
                this.netLatencyObject.ResponseRecieved += new EventHandler(netLatencyObject_ResponseRecieved);
                DistributionSession.DistributeObject(this.netLatencyObject);
            }

            Start(GetTime());
        }

       
        private double GetTime()
        {
            return DateTime.Now.TimeOfDay.TotalMilliseconds;
        }

        private void Start(double time)
        {
            //set start time
            this.timePacketSend = time;
            this.netLatencyObject.TestLatencyProp = (int)time;
        }

        private void netLatencyObject_ResponseRecieved(object sender, EventArgs e)
        {
            this.timeLastRoundtrip = (float) (GetTime() - this.timePacketSend);
        }

        /// <summary>
        /// Gets the last meassured roundtrip-latency to server (and back).
        /// </summary>
        /// <returns></returns>
        public float GetLatency()
        {
            return this.timeLastRoundtrip;
        }


    }

    /// <summary>
    /// A test distributable object to meassure latency values.
    /// </summary>
    public class NetLatencyObject : DistributableObject
    {
        public NetLatencyObject()
        {
            this._testLatencyProp = DistributableProperty<int>.Register("TestLatencyProp", this, NetChannel.ReliableInOrder1);
        }

        [Distribute]
        public int TestLatencyProp
        {
            get
            {
                return this._testLatencyProp.GetValue();
            }
            set
            {
                if (this._testLatencyProp.SetValue(value))
                    if (ResponseRecieved != null)
                        ResponseRecieved(this, null);
            }
        }

        public event EventHandler ResponseRecieved;

        private DistributableProperty<int> _testLatencyProp;
    }

}
